//
//  KLCurrencyCell.m
//  KLCurrency
//
//  Created by apple on 2017/12/2.
//  Copyright © 2017年 bonc. All rights reserved.
//

#import "KLCurrencyCell.h"

#import "KLNavigationController.h"

#import "KLNumberPad.h"
#import "KLCurrencyEntity.h"
#import "KLCurrencyCell.h"

#import "KLArithmeticTextField.h"
#import "KLRoundImageView.h"

#import "Masonry.h"

static const CGFloat constraintToMargins = 15.0f;
static const CGFloat accessoryViewFontSize = 16.0f;

static const CGFloat animateDurationTime = 0.1f;
static const CGFloat animateOffsetX = 3.0f;

@interface KLCurrencyCell () <UITextFieldDelegate>

@property (strong, nonatomic) CABasicAnimation *animate;
@property (strong, nonatomic) CABasicAnimation *animateArithmetic;
@property (assign, nonatomic) CGFloat amountInputMaxWidth;//金额输入框最长长度
@property (assign, nonatomic) CGFloat abbreviationLabelHiddenWidth;//金额长度超过该值时，缩写隐藏

@property (weak, nonatomic) IBOutlet KLRoundImageView *flagImageView;//国旗
@property (weak, nonatomic) IBOutlet UIImageView *locationImageView;//定位
@property (weak, nonatomic) IBOutlet UILabel *abbreviationLabel;//货币缩写
@property (weak, nonatomic) IBOutlet UILabel *symbolLabel;//货币单位+货币名称
@property (weak, nonatomic) IBOutlet UIView *selectedBg;

@property (weak, nonatomic) IBOutlet KLArithmeticTextField *amountInput;//数值
@property (weak, nonatomic) IBOutlet KLArithmeticTextField *arithmeticInput;//计算式

@end

@implementation KLCurrencyCell

#pragma mark - init

+ (instancetype)cellWithTableView:(UITableView *)tableView {
    KLCurrencyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"currency"];
    return cell;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setupUI];
        [self setupGesture];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
        [self setupGesture];
    }
    return self;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
        [self setupGesture];
    }
    return self;
}

- (void)setupUI {
    //补充设置
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    self.amountInput.font = [UIFont fontWithName:@"Arial" size:26.0f];
    
    //右划显示-切换货币
    UIView *leftView = [[UIView alloc] init];
    leftView.backgroundColor = UIColorFromRGB(0X8891A7);
    [self.contentView addSubview:leftView];
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kScreenWidth);
        make.size.equalTo(self.contentView);
        make.centerY.mas_equalTo(0);
    }];
    UIImageView *leftViewIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"change_currency"]];
    [leftView addSubview:leftViewIcon];
    [leftViewIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-constraintToMargins);
        make.centerY.mas_equalTo(0);
    }];
    UILabel *leftLable = [[UILabel alloc] init];
    leftLable.text = @"切换货币";
    leftLable.textColor = [UIColor whiteColor];
    leftLable.font = [UIFont systemFontOfSize:accessoryViewFontSize];
    [leftView addSubview:leftLable];
    [leftLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.right.equalTo(leftViewIcon.mas_left).with.offset(-constraintToMargins);
    }];
    
    //左划显示-数据详情
    UIView *rightView = [[UIView alloc] init];
    rightView.backgroundColor = UIColorFromRGB(0X8891A7);
    [self.contentView addSubview:rightView];
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kScreenWidth);
        make.size.equalTo(self.contentView);
        make.centerY.mas_equalTo(0);
    }];
    UIImageView *rightViewIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rate_detail"]];
    [rightView addSubview:rightViewIcon];
    [rightViewIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(constraintToMargins);
        make.centerY.mas_equalTo(0);
    }];
    UILabel *rightLable = [[UILabel alloc] init];
    rightLable.text = @"汇率详情";
    rightLable.textColor = [UIColor whiteColor];
    rightLable.font = [UIFont systemFontOfSize:accessoryViewFontSize];
    [rightView addSubview:rightLable];
    [rightLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.equalTo(rightViewIcon.mas_right).with.offset(constraintToMargins);
    }];
}

//根据模型数据设置视图
- (void)setCurrencyEntity:(KLCurrencyEntity *)currencyEntity {
    _currencyEntity = currencyEntity;
    self.abbreviationLabel.text = currencyEntity.abbreviation;
    self.flagImageView.image = [UIImage imageNamed:currencyEntity.abbreviation];
    if (currencyEntity.amount.length > 0 && currencyEntity.amount.floatValue > 0.000001) {
        //存在输入
        self.amountInput.text = currencyEntity.amount;
        //这边可以做一个numberfommater的转换
        //TODO转换结束后进行一个是否超出最大长度检测，如果是，进行抖动警告
    } else {
        //没有输入设置为默认值
        self.amountInput.text = nil;
        self.amountInput.placeholder = kDefaultAmountText;
    }
    
    if (currencyEntity.isLocal) {
        //这边进行定位判断
        self.locationImageView.hidden = NO;
    } else {
        self.locationImageView.hidden = YES;
    }
    
    self.symbolLabel.text = [NSString stringWithFormat:@"%@ %@",currencyEntity.name, currencyEntity.symbol];
}

- (void)setAmountInputText:(NSString *)amountInputText {
    _amountInputText = amountInputText;
    self.amountInput.text = amountInputText;
}

- (void)setArithmeticInputText:(NSString *)arithmeticInputText {
    _arithmeticInputText = arithmeticInputText;
    self.arithmeticInput.text = arithmeticInputText;
}

- (void)setAmountInputPlaceholder:(NSString *)amountInputPlaceholder {
    _amountInputPlaceholder = amountInputPlaceholder;
    self.amountInput.placeholder = amountInputPlaceholder;
}

- (void)amountInputDidBecomeFirstResponder {
    [self.amountInput becomeFirstResponder];
}

- (void)arithmeticInputDidBecomeFirstResponder {
    [self.arithmeticInput becomeFirstResponder];
}


//复用清空资源
- (void)prepareForReuse {
    [super prepareForReuse];
    self.flagImageView.image = nil;
    self.amountInput.text = nil;
    self.symbolLabel.text = nil;
    self.abbreviationLabel.text = nil;
    self.locationImageView.image = nil;
}

#pragma mark - Gesture

- (void)setupGesture {
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    [self addGestureRecognizer:pan];
}

- (void)panAction:(UIPanGestureRecognizer *)pan {
    CGPoint center = CGPointMake(kScreenWidth * 0.5, self.center.y);
    CGFloat minMoveHorizonalDistance = kScreenWidth * 0.25;
    
    switch (pan.state) {
        case UIGestureRecognizerStateChanged: {
            CGPoint translation = [pan translationInView:self.contentView];
            self.center = CGPointMake(center.x + translation.x, center.y);
            break;
        }
        case UIGestureRecognizerStateEnded: {
            if (self.center.x - center.x > minMoveHorizonalDistance) {
                //右划超过屏幕1/4
                [UIView animateWithDuration:kCellMoveOutAnimationDuration animations:^{
                    self.center = CGPointMake(center.x * 3, center.y);
//                    self.center = CGPointMake(center.x * 2, center.y);
                } completion:^(BOOL finished) {
                    if ([self.delegate respondsToSelector:@selector(changeCurrency:)]) {
                        [self.delegate changeCurrency:self];
                    }
                }];
                
            } else if (center.x - self.center.x > minMoveHorizonalDistance) {
                //左划超过屏幕1/4
                [UIView animateWithDuration:kCellMoveOutAnimationDuration animations:^{
                    self.center = CGPointMake(- center.x, center.y);
//                    self.center = CGPointMake(0, center.y);
                } completion:^(BOOL finished) {
                    if ([self.delegate respondsToSelector:@selector(showCurrencyDetail:)]) {
                        [self.delegate showCurrencyDetail:self];
                    }
                }];
            } else {
                //距离不达标做弹簧动画
                [UIView animateWithDuration:kCellSpringAnimationDuration delay:kCellSpringAnimationDelay usingSpringWithDamping:kCellSpringAnimationDamping initialSpringVelocity:kCellSpringAnimationInitialVelocity options:UIViewAnimationOptionCurveEaseInOut animations:^{
                    self.center = center;
                } completion:nil];
            }
            break;
        }
        default:
            break;
    }
}

#pragma mark - show set
//amount过长隐藏货币缩写
- (BOOL)shouldHideAbbreviationLabelWithDecimalAmountText:(NSString *)text {
    CGFloat amountWidth = [self amountStringWidthWithDecimalAmountText:text];
    CGFloat abbreviationWidth = [self abbreviationStringWidth];
    if ((amountWidth + constraintToMargins + CGRectGetMidX(self.abbreviationLabel.frame) + abbreviationWidth)>= kScreenWidth)  {
        // 超出缩写右界
        if ((amountWidth + constraintToMargins + CGRectGetMidX(self.abbreviationLabel.frame))>= kScreenWidth) {
            //超出缩写左界
            CGFloat textFieldMaxWidth = kScreenWidth - constraintToMargins - CGRectGetMidX(self.abbreviationLabel.frame);
            CGFloat scale = 1 - textFieldMaxWidth / self.amountInput.frame.size.width;
            CAGradientLayer *maskLayer = [CAGradientLayer layer];
            maskLayer.frame = CGRectMake(0, 0, self.amountInput.frame.size.width, self.amountInput.frame.size.height);
            [maskLayer setColors:@[(id)[UIColor colorWithWhite:0 alpha:1].CGColor, (id)[UIColor clearColor].CGColor]];
            maskLayer.startPoint = CGPointMake(scale + 0.1, 0);
            maskLayer.endPoint = CGPointMake(scale, 0);
            self.amountInput.layer.mask = maskLayer;
        }
        return YES;
    }
    return NO;
}

//amount过长禁止输入
- (BOOL)shouldForbidamountInput:(NSString *)text {
    CGFloat amountLength = [self amountStringWidthWithDecimalAmountText:text];
    CGFloat amountLengthMax = [self amountStringMaxWidth];
    if ((amountLengthMax - amountLength) >0) {
        return NO;
    }else {
        return YES;
    }
}

//计算数量文字长度
- (CGFloat)amountStringWidthWithDecimalAmountText:(NSString *)text {
    UIFont *font = self.amountInput.font;
    CGSize size = [text boundingRectWithSize:self.amountInput.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:nil].size;
    return size.width;
}

//计算数量文字最大长度
- (CGFloat)amountStringMaxWidth {
    return kScreenWidth - 80 - [self abbreviationStringWidth];
}

//计算缩写文字长度
- (CGFloat)abbreviationStringWidth {
    NSString *str = self.abbreviationLabel.text;
    UIFont *font = self.abbreviationLabel.font;
    CGSize size = [str boundingRectWithSize:self.abbreviationLabel.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:nil].size;
    return size.width;
}

- (void)amountIllegalInputAnimation {
    [self.amountInput.layer addAnimation:self.animate forKey:self.animate.keyPath];
}

- (void)arithmeticIllegalInputAnimation {
    [self.arithmeticInput.layer addAnimation:self.animateArithmetic forKey:self.animateArithmetic.keyPath];
}

- (CABasicAnimation *)animate {
    if (_animate == nil) {
        _animate = [CABasicAnimation animationWithKeyPath:@"position.x"];
        _animate.fromValue = @(self.amountInput.layer.position.x - animateOffsetX);
        _animate.toValue = @(self.amountInput.layer.position.x + animateOffsetX);
        _animate.duration = animateDurationTime;
        _animate.repeatCount = 2;
        _animate.autoreverses = YES;
        _animate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    }
    return _animate;
}

- (CABasicAnimation *)animateArithmetic {
    if (_animateArithmetic == nil) {
        _animateArithmetic = [CABasicAnimation animationWithKeyPath:@"position.x"];
        _animateArithmetic.fromValue = @(self.arithmeticInput.layer.position.x - animateOffsetX);
        _animateArithmetic.toValue = @(self.arithmeticInput.layer.position.x + animateOffsetX);
        _animateArithmetic.duration = animateDurationTime;
        _animateArithmetic.repeatCount = 2;
        _animateArithmetic.autoreverses = YES;
        _animateArithmetic.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    }
    return _animateArithmetic;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    if (selected) {
        self.selectedBg.hidden = NO;
    } else {
        self.selectedBg.hidden = YES;
    }

    // Configure the view for the selected state
}

@end
